<template>
  <div class="q-layout-padding">
    <t-form
      style="max-width: 300px"
      @submit="onSubmit"
      @reset="onReset"
      @validation-success="onValidationChange(true)"
      @validation-error="onValidationChange(false)"
    >
      <t-card bordered>
        <t-card-section>
          <t-banner v-if="submitted" class="bg-positive" dark rounded
            >Form submitted</t-banner
          >
          <t-banner v-else class="bg-negative" dark rounded
            >Form NOT submitted</t-banner
          >
        </t-card-section>

        <t-card-section v-if="validated !== null">
          <t-banner v-if="validated === true" class="bg-positive" dark rounded
            >Form valid</t-banner
          >
          <t-banner v-else class="bg-negative" dark rounded
            >Form invalid</t-banner
          >
        </t-card-section>

        <t-card-section>
          <t-toggle v-model="async" label="Async rules" />

          <t-input
            v-model="modelValue"
            :rules="validationRules"
            filled
            label="Input"
            hint="Hint: field is required"
            lazy-rules
            reactive-rules
          />
        </t-card-section>

        <t-card-actions>
          <t-btn class="col" type="reset" color="grey-8" flat label="Reset" />

          <t-btn
            class="col"
            type="submit"
            color="primary"
            unelevated
            label="Submit"
          />
        </t-card-actions>
      </t-card>
    </t-form>
  </div>
</template>

<script>
  const wait = (delay = 3000) =>
    new Promise(resolve => setTimeout(resolve, delay));
  const required = val =>
    (typeof val === 'string' && val.length > 0) || 'Field is required';
  const asyncValidate = val => wait().then(() => required(val));

  export default {
    data() {
      return {
        modelValue: '',
        submitted: false,
        validated: null,
        async: true,
      };
    },

    computed: {
      validationRules() {
        return this.async === true ? [asyncValidate] : [required];
      },
    },

    methods: {
      onReset() {
        this.modelValue = '';
        this.submitted = false;
        this.validated = null;
      },

      onSubmit() {
        console.log('onSubmit');
        this.submitted = true;
      },

      onValidationChange(state) {
        console.log('@validation-' + (state === true ? 'success' : 'error'));
        this.submitted = false;
        this.validated = state;
      },
    },
  };
</script>
